﻿from pgmpy.factors.discrete import TabularCPD
from pgmpy.models import BayesianNetwork
from pgmpy.inference import BeliefPropagation
print('Belief Propagation，启动！')
bayesian_model = BayesianNetwork([('A', 'J'), ('R', 'J'), ('J', 'Q'),
                                ('J', 'L'), ('G', 'L')])
cpd_a = TabularCPD('A', 2, [[0.2], [0.8]])
cpd_r = TabularCPD('R', 2, [[0.4], [0.6]])
cpd_j = TabularCPD('J', 2,
                   [[0.9, 0.6, 0.7, 0.1],
                    [0.1, 0.4, 0.3, 0.9]],
                   ['R', 'A'], [2, 2])
cpd_q = TabularCPD('Q', 2,
                   [[0.9, 0.2],
                    [0.1, 0.8]],
                   ['J'], [2])
cpd_l = TabularCPD('L', 2,
                   [[0.9, 0.45, 0.8, 0.1],
                    [0.1, 0.55, 0.2, 0.9]],
                   ['G', 'J'], [2, 2])
cpd_g = TabularCPD('G', 2, [[0.6], [0.4]])
bayesian_model.add_cpds(cpd_a, cpd_r, cpd_j, cpd_q, cpd_l, cpd_g)
belief_propagation = BeliefPropagation(bayesian_model)
pb1=belief_propagation.query(variables=['J', 'Q'],
                         evidence={'A': 0, 'R': 0, 'G': 0, 'L': 1})
print(pb1)
pb2=belief_propagation.query(variables=['J', 'Q'],
                         evidence={'A': 0, 'R': 0, 'G': 0, 'L': 1},joint=False)
print(pb2['J'].values)

from pgmpy.models import DynamicBayesianNetwork as DBN
from pgmpy.inference import DBNInference
print('Belief Propagation in DBN，启动！')
dbnet = DBN()
dbnet.add_edges_from([(('Z', 0), ('X', 0)), (('X', 0), ('Y', 0)),
                      (('Z', 0), ('Z', 1))])
z_start_cpd = TabularCPD(('Z', 0), 2, [[0.5], [0.5]])
x_i_cpd = TabularCPD(('X', 0), 2, [[0.6, 0.9],
                                   [0.4, 0.1]],
                     evidence=[('Z', 0)],
                     evidence_card=[2])
y_i_cpd = TabularCPD(('Y', 0), 2, [[0.2, 0.3],
                                   [0.8, 0.7]],
                     evidence=[('X', 0)],
                     evidence_card=[2])
z_trans_cpd = TabularCPD(('Z', 1), 2, [[0.4, 0.7],
                                       [0.6, 0.3]],
                     evidence=[('Z', 0)],
                     evidence_card=[2])
dbnet.add_cpds(z_start_cpd, z_trans_cpd, x_i_cpd, y_i_cpd)
dbnet.initialize_initial_state()
dbn_inf = DBNInference(dbnet)
pb3=dbn_inf.query([('X', 0)], {('Y', 0):0, ('Y', 1):1, ('Y', 2):1})
print(pb3[('X', 0)].values)
